#-*- coding: utf-8 -*-


import tarfile
import os
import re
import sys



TMP_DIR='c:\\'
if __name__=='__main__':
	TAR_FILE_PATH = sys.argv[1]
	PATTERN_PATH =  sys.argv[2]

	tarfile = tarfile.open(TAR_FILE_PATH)
	tarfile.extractall(path=TMP_DIR)
	tarfile.close()
	os.chdir(TMP_DIR+'x5')
	
	dir_list = os.listdir('.')
	for dir2 in dir_list :
		os.chdir(dir2)
		for ini in os.listdir('.'):
			port = ''
			host = ''
			if ini.rfind('ini') < 0 :
				continue
				
			ini_file = open(ini)
			ini_lines = ini_file.readlines()
			ini_file.close()
			xsh_file_name = ini[:ini.rfind('.')]+'.xsh'
			for line in ini_lines :
				p = re.match(r'D\:\"\[SSH2\] Port\"=(\w+)', line)
				if p :
					port = int(p.group(1),16)
					
				h = re.match(r'S:"Hostname"=(\w+.\w+.\w+.\w+)', line)
				if h :
					host = h.group(1)
	
			pattern_file =open(PATTERN_PATH,'r')
			pattern_lines = pattern_file.readlines()
			pattern_file.close()
			for i in xrange(0, len(pattern_lines)) :
				pattern_lines[i] = re.sub(r'^Port=(\w+)',r'Port='+str(port), pattern_lines[i])
				pattern_lines[i] = re.sub(r'^Host=(\w+.\w+.\w+.\w+)',r'Host='+host, pattern_lines[i])
				
			op_file = open(xsh_file_name, 'wb+')
			for line in pattern_lines :
				op_file.write(line)
			
			op_file.close()
			os.remove(ini)
		os.chdir('..')
	

